<template>
  <el-table highlight-current-row :show-summary='summary' :summary-method="getSummaries" sum-text="合计" :data="data" v-loading.body="loading" border size="mini">
    <el-table-column v-for="(c,index) in columns" :key="index" align="center" :label="c.label">
      <template slot-scope="scope">
        <viewer v-if="c.type=='image'" class="images" :class="[scope.row.ratio<1?'h':'w',scope.row.is_on_sale==0?'off_sale':'']">
          <img :src="scope.row[c.dtcol[0]]" :data-source="scope.row[c.dtcol[1]]" :key="scope.row[c.dtcol[1]]" class="image"
            :alt="scope.row[c.dtcol[1]].split('?image=').pop()">
        </viewer>
        <router-link v-else-if="c.link" :to="{name:c.link,query:{row:scope.row,col:c.dtcol,global:global,routerflag:true}}">
          <span :class="c.colornum&&(getvalue(scope,c)*1<0?'bad':'ok')">
            {{getvalue(scope,c)}}
          </span>
        </router-link>
        <span v-else :class="c.colornum&&(getvalue(scope,c)*1<0?'bad':'ok')">
          {{getvalue(scope,c)}}
        </span>
      </template>
    </el-table-column>
  </el-table>
</template>
<script>
export default {
  name: 'DjSimpleTable',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array,
      required: true,
      default() {
        return [];
      }
    },
    data: {
      type: Array,
      required: true,
      default() {
        return [];
      }
    },
    global: {
      type: Object,
      default() {
        return {};
      }
    },
    summary: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {};
  },
  methods: {
    getvalue(scope, c) {
      let v = c.dtkey ? scope.row[c.dtcol][c.dtkey] : scope.row[c.dtcol];
      if (c.isnum) v = this.keepTwoNum(v);
      return v;
    },
    keepTwoNum(value) {
      value = Number(value);
      return value.toFixed(2);
    },
    getSummaries(param) {
      const { columns, data } = param;
      const sums = [];
      this.columns.forEach((c, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        const values = data.map(item => (c.summary ? Number(c.dtkey ? item[c.dtcol][c.dtkey] : item[c.dtcol]) : 'NaN')); // Number(c.dtkey ? item[c.dtcol][c.dtkey] : item[c.dtcol])
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          if (c.isnum) sums[index] = this.keepTwoNum(sums[index]);
        } else {
          sums[index] = ''; //非数字不显示
        }
      });
      return sums;
    }
  }
};
</script>
<style scoped>
.cell a {
  color: #409eff;
}
.ok {
  color: #67c23a;
}
.bad {
  color: #f56c6c;
}
</style>